package com.xxmw.transaction.common.utils;

import com.xxmw.transaction.common.excep.service.TransactionException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

/**
 * 数据校验
 *
 * @author francis
 */
public abstract class Assert {

    public static void isBlank(String str, String message) {
        if (StringUtils.isBlank(str)) {
            throw new TransactionException(message);
        }
    }

    public static void isNull(Object object, String message) {
        if (object == null) {
            throw new TransactionException(message);
        }
    }
    
    public static boolean isNullOrEmpty(Object value) {
		if (null == value) {
			return true;
		}
		if ((value instanceof CharSequence)) {
			return isBlank((CharSequence) value);
		}
		if (isCollectionsSupportType(value)) {
			return CollectionUtils.sizeIsEmpty(value);
		}
		return false;
	}
    
    public static boolean isNotNullOrEmpty(Object value) {
		return !isNullOrEmpty(value);
	}

    public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    
	private static boolean isCollectionsSupportType(Object value) {
		boolean isCollectionOrMap = ((value instanceof Collection)) || ((value instanceof Map));

		boolean isEnumerationOrIterator = ((value instanceof Enumeration)) || ((value instanceof Iterator));

		return (isCollectionOrMap) || (isEnumerationOrIterator) ||

				(value.getClass().isArray());
	}
}
